package com.zhicheng.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.zhicheng.exception.BaseException;
import com.zhicheng.mapper.AddressBookMapper;
import com.zhicheng.pojo.AddressBook;
import com.zhicheng.pojo.result.PageResult;
import com.zhicheng.service.AddressBookService;
import com.zhicheng.utils.ThreadLocalUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;


import java.util.List;


@Service
public class AddressBookServiceImpl implements AddressBookService {

    @Autowired
    private AddressBookMapper addressBookMapper;

    @Override
    public List<AddressBook> list() {
        Long userId = ThreadLocalUtil.getCurrentId();
        List<AddressBook> addressBooks = addressBookMapper.getByUserId(userId);
        return addressBooks;
    }

    @Override
    public void addAddress(AddressBook addressBook) {
        Long userId = ThreadLocalUtil.getCurrentId();
        addressBook.setUserId(userId);
        List<AddressBook> addressBooks = addressBookMapper.getByUserId(userId);
        for (AddressBook address : addressBooks){
            if (address.getIsDefault() == 1 && addressBook.getIsDefault() == 1){
                throw new BaseException("已有默认地址，不可再新增默认地址");
            }
        }
        addressBookMapper.addAddress(addressBook);
    }

    @Override
    public PageResult<AddressBook> getByUserId(int page, int pageSize) {
        //1.创建PageResult对象
        PageResult<AddressBook> pageResult =new PageResult<>();
        //2.开启分页查询PageHelper
        PageHelper.startPage(page, pageSize);
        Long userId = ThreadLocalUtil.getCurrentId();
        List<AddressBook> addressBookList = addressBookMapper.getByUserId(userId);
        //Page中提供了方法，可以获取PageHelper分页查询后得到的总记录数和当前页数据
        Page<AddressBook> p = (Page<AddressBook>) addressBookList;
        //把数据填充到PageResult对象中
        pageResult.setTotal(p.getTotal());
        pageResult.setItems(p.getResult());
        pageResult.setPages(p.getPages());
        pageResult.setPage(p.getPageNum());
        pageResult.setPageSize(p.getPageSize());
        return pageResult;

    }

    @Override
    public void updateAddress(AddressBook addressBook) {
        addressBookMapper.updateAddress(addressBook);
    }

    @Override
    public void deleteAddress(Long id) {
        addressBookMapper.deleteAddress(id);
    }
}


